package m.member.manage.action;

import m.common.action.ActionMeta;
import m.common.action.VueResult;
import m.common.model.util.FromQueryList;
import m.common.model.util.QueryCondition;
import m.common.model.util.QueryOrder;
import m.html.VueCollectResult;
import m.html.VueListResult;
import m.html.VueTabResult;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.list.ListButton;
import m.html.list.ListCount;
import m.html.list.ListElement;
import m.html.list.SuccessMethod;
import m.html.tab.TabItem;
import m.member.manage.model.LevelUpSet;
import m.member.manage.model.ServeGoods;
import m.member.manage.model.ServeType;
import m.member.order.model.OrderInfo;
import m.system.db.DataRow;
import m.system.db.SqlBuffer;
import m.system.exception.MException;
import m.system.util.DateUtil;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import manage.action.ManageAction;
import manage.model.AdminLogin;
import manage.model.OrgGroupView;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@ActionMeta(name = "member/manage/index")
public class IndexAction extends ManageAction {
    /**
     * 首页数据
     */
    public JSONMessage getIndexMap() throws MException, SQLException {
        AdminLogin admin=getSessionAdmin();
        OrgGroupView org=getSessionOrgGroup();
        if(null==org|| ObjectUtil.isEmptyOid(org.getDept()))
            throw new MException(this.getClass(),"无店铺信息");
        OrgGroupView dept=org.getDept();
        Date date=new Date();
        String ym= DateUtil.format(date,"yyyy-MM"),m=DateUtil.format(date,"MM"),d=DateUtil.format(date,"dd");
        Map<String,Object> data=new HashMap<>();
        DataRow dr=new SqlBuffer()
            .append("select ")
            .append(" ifnull(sum(case when date_format(input_date,'%d')=? and input_admin_oid=? then 1 else 0 end),0) adminDayNum,",d,admin.getOid())
            .append(" ifnull(sum(case when date_format(input_date,'%d')=? and input_admin_oid=? then pay_amount else 0 end),0) adminDayAmount,",d,admin.getOid())
            .append(" ifnull(sum(case when date_format(input_date,'%m')=? and input_admin_oid=? then 1 else 0 end),0) adminMonthNum,",m,admin.getOid())
            .append(" ifnull(sum(case when date_format(input_date,'%m')=? and input_admin_oid=? then pay_amount else 0 end),0) adminMonthAmount,",m,admin.getOid())
            .append(" ifnull(sum(case when date_format(input_date,'%d')=? then 1 else 0 end),0) deptDayNum,",d)
            .append(" ifnull(sum(case when date_format(input_date,'%d')=? then pay_amount else 0 end),0) deptDayAmount,",d)
            .append(" ifnull(sum(case when date_format(input_date,'%m')=? then 1 else 0 end),0) deptMonthNum,",m)
            .append(" ifnull(sum(case when date_format(input_date,'%m')=? then pay_amount else 0 end),0) deptMonthAmount",m)
            .append("from to_order_info")
            .append("where date_format(input_date,'%Y-%m')=? and input_dept_oid=?",ym,dept.getOid())
            .queryFirstRow();
        if(null!=dr){
            data.put("adminDayNum",dr.get(Integer.class,"adminDayNum"));
            data.put("adminDayAmount",dr.get(Double.class,"adminDayAmount"));
            data.put("adminMonthNum",dr.get(Integer.class,"adminMonthNum"));
            data.put("adminMonthAmount",dr.get(Double.class,"adminMonthAmount"));
            data.put("deptDayNum",dr.get(Integer.class,"deptDayNum"));
            data.put("deptDayAmount",dr.get(Double.class,"deptDayAmount"));
            data.put("deptMonthNum",dr.get(Integer.class,"deptMonthNum"));
            data.put("deptMonthAmount",dr.get(Double.class,"deptMonthAmount"));
        }
        return new JSONMessage(0)
                .push("dataMap",data)
                .push("date",DateUtil.format(date,"yyyy年MM月dd日 EEEE"))
                .push("admin",admin)
                .push("dept",dept)
                .push("org",org.getOrg());
    }
    public VueResult orderCollectTab(){
        JSONMessage params=new JSONMessage()
            .push("echarts_x",new String[]{"inputDate"})
            .push("echarts_y1",new String[]{"orderAmount"})
            .push("echarts_y2",new String[]{"orderNum"})
            .push("simple","Y").push("height","200px");
        VueTabResult tab=new VueTabResult("近90天已确认订单");
        tab.setSubTitle("{{tabs.names[indexKey]}}");
        tab.addItems(new TabItem("adminOrderCollect","我的业绩",actionUrl("toEcharts"),
            new JSONMessage().push("method","adminOrderCollect").push("params",params)));
        tab.addItems(new TabItem("deptOrderCollect","店铺业绩",actionUrl("toEcharts"),
            new JSONMessage().push("method","deptOrderCollect").push("params",params)));
        return tab;
    }
    public VueResult adminOrderCollect() throws Exception {
        return orderCollect("adminOrderCollect");
    }
    public VueResult deptOrderCollect() throws Exception {
        return orderCollect("deptOrderCollect");
    }
    /*
     * 近90天订单金额
     */
    private VueResult orderCollect(String method) throws Exception {
        AdminLogin admin=getSessionAdmin();
        OrgGroupView org=getSessionOrgGroup();
        if(null==org|| ObjectUtil.isEmptyOid(org.getDept()))
            throw new MException(this.getClass(),"无店铺信息");
        OrgGroupView dept=org.getDept();
        FromQueryList from=FromQueryList.fromGroup("a",OrderInfo.class);
        from.addCondition("#{a.inputDate}>=? and #{a.status}='Y'",DateUtil.getAddDate(new Date(),-90));
        from.addCondition("#{a.inputDept.oid}=?",dept.getOid());
        if(method.indexOf("admin")==0)
            from.addCondition("#{a.inputAdmin.oid}=?",admin.getOid());
        //
        VueCollectResult result=getVueCollectResult("近90天已确认订单", from,actionUrl(method));
        result.setFunction(true,true);
        result.addCol(collectDateColumn("录入时间", "#{a.inputDate} inputDate", 100, true));
        result.addCol(collectNumberColumn("订单数量", "COUNT(#{a.oid}) orderNum", 100, true));
        result.addCol(collectNumberColumn("订单金额", "SUM(#{a.payAmount}) orderAmount", 100, true));
        return result;
    }
    /*
     * 会员升级配置
     */
    public VueResult levelUpSetList() throws Exception {
        VueListResult result=getVueListResult("会员升级配置", LevelUpSet.class,actionUrl("levelUpSetList"),true);
        result.hideHead();
        result.setFunction(false,false);
        result.addQueryFields("beforeLevel.*","afterLevel.*","*");
        result.addCol(toElementColumn("会员",
            new ListElement("a-tag")
                .addAttr(":color","record.beforeLevel.color")
                .addText("{{record.beforeLevel.name}}"),
            new ListElement("a-tag")
                .addAttr(":color","dict('color',record.beforeLevel.color)")
                .addText("{{record.beforeLevel.discount}}%")
        ).setAlign(Align.CENTER));
        result.addCol(toElementColumn("升级后",
            new ListElement("a-tag")
                .addAttr(":color","record.afterLevel.color")
                .addText("{{record.afterLevel.name}}"),
            new ListElement("a-tag")
                .addAttr(":color","dict('color',record.afterLevel.color)")
                .addText("{{record.afterLevel.discount}}%")
        ).setAlign(Align.CENTER));
        result.addCol(toElementColumn("升级条件",
            new ListElement("div").addAttr("v-if","record.useMoney").addText("消费金额：{{record.useMoney}}元"),
            new ListElement("div").addAttr("v-if","record.orderNum").addText("订单数：{{record.orderNum}}单")
        ));
        result.addCondition(QueryCondition.eq("status","0"));
        result.addOrder(QueryOrder.asc("afterLevel.discount"));
        return result;
    }
    /*
     * 服务商品管理
     */
    public VueResult serveGoodsList() throws Exception {
        VueListResult result=getVueListResult("服务项目", ServeGoods.class,actionUrl("serveGoodsList"));
        result.hideHead();
        result.setFunction(false,false);
        result.addQueryFields("type.color","type.name");
        result.addCol(toTextColumn("类型", "type.oid", 100, true)
            .addElement(new ListElement("a-tag")
                .addAttr(":color","record.type.color")
                .addText("{{record.type.name}}")
            )
            .setDictType(ServeType.class)
            .setAlign(Align.CENTER)
        );
        result.addCol(toTextColumn("标题", "title", 150, true));
        result.addCol(toTextColumn("描述", "description", 250, true));
        result.addCol(toNumberColumn("单价","price",100,true).setCount(ListCount.NONE));
        result.addCol(toIntegerColumn("优惠","discount",100,true).setCount(ListCount.NONE)
            .addElement(ListElement.test("record.discount",
                new ListElement("a-tag")
                .addAttr("color","processing")
                .addText("{{record.discount}}%")
            )).setAlign(Align.CENTER)
        );
        result.addCol(toElementColumn("优惠后",
            new ListElement("span").addText("{{formatNumber(record.price*(100-record.discount)/100,'#,##0.00')}}")
        ).setAlign(Align.RIGHT));
        result.addCondition(QueryCondition.eq("status","0"));
        //排序 result.addOrder
        //查询条件 result.addCondition
        return result;
    }
}
